package com.tianfei.crowd.mvc.interceptor;

import com.tianfei.crowd.constant.CrowdConstants;
import com.tianfei.crowd.entity.Admin;
import com.tianfei.crowd.exception.AccessForbiddenException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * 登录拦截器，在使用SpringSecurity后，不在使用该自定义拦截器
 *
 * @author: Herz
 * @date: 2021/7/8 19:13
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1、通过request获取session对象
        HttpSession session = request.getSession();

        // 2、通过session尝试获取Admin对象
        Admin admin = (Admin) session.getAttribute(CrowdConstants.MESSAGE_ATTR_LOGIN);

        // 3、判断Admin是否为null
        if (admin == null){
            // 4、抛出异常
            throw new AccessForbiddenException(CrowdConstants.MESSAGE_ACCESS_FORBIDDEN);
        }

        // 5、如果Admin不为null，则返回true
        return true;
    }
}
